<template>
  <div class="login">
      <div class="content">
        <div class="box">
          <div class="list">
            <div class="left">
              <div class="time">
                {{date+ '  '}}{{time}}
              </div>
              <!--            <div class="logo">-->
              <img src="@/assets/img/login/logo.jpeg" alt="">
              <!--            </div>-->
              <!--            <h2 class="title">在线点餐</h2>-->
            </div>
            <div class="right">
              <div class="form">
                <a-form v-if="status === 1"
                        :model="loginForm"
                        ref="loginRef"
                        :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-form-item label="手机号" name="mobile">
                    <a-input v-model:value="loginForm.mobile" placeholder="请输入手机号" />
                  </a-form-item>
                  <a-form-item label="密码">
                    <a-input v-model:value="loginForm.password" placeholder="请输入密码" />
                  </a-form-item>
                  <a-form-item label="验证码">
                    <div class="code">
                      <a-input v-model:value="loginForm.captcha" placeholder="请输入验证码" />
                      <div class="captcha" @click="refreshCode">
                        <img :src="imgUrl" alt="">
                      </div>
                    </div>
                  </a-form-item>
                  <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
<!--                    <img :src="imgUrl" alt="">-->
                    <a-button type="primary" @click.prevent="onSubmit">登录</a-button>
                    <a-button style="margin-left: 10px" @click="reset">重置</a-button>
                    <a-button style="margin-left: 10px" @click="forget">忘记密码</a-button>
                    <!--        <a-button style="margin-left: 10px" @click="reset">用户注册</a-button>-->
                  </a-form-item>
                </a-form>
<!--       注册表单         -->
                <a-form
                  :model="registerForm"
                  :rules="registerRules"
                  ref="registerRef"
                  v-if="status === 2"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol">
                  <a-form-item label="邮箱" name="email">
                    <a-input v-model:value="registerForm.email" placeholder="请输入邮箱" />
                  </a-form-item>
                  <a-form-item label="手机号" name="mobile">
                    <a-input-search
                      v-model:value="registerForm.mobile"
                      placeholder="请输入手机号"
                      enter-button="获取验证码"
                      size="large"
                      :loading=codeLoading
                      @search="getCode"
                    />
                  </a-form-item>
                  <a-form-item label="验证码" name="code">
                    <a-input v-model:value="registerForm.code" placeholder="请输入验证码" />
                  </a-form-item>
                  <a-form-item label="密码" name="password">
                    <a-input v-model:value="registerForm.password" placeholder="请输入密码" />
                  </a-form-item>
                  <a-form-item label="昵称" name="username">
                    <a-input v-model:value="registerForm.username" placeholder="请输入用户名" />
                  </a-form-item>
                  <a-form-item label="性别" name="sex">
                    <a-radio-group v-model:value="registerForm.sex">
                      <a-radio value="0">男</a-radio>
                      <a-radio value="1">女</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                    <a-button type="primary" @click.prevent="register">注册</a-button>
                    <a-button style="margin-left: 10px" @click="resetRegister">重置</a-button>
                  </a-form-item>
                </a-form>

<!--      忘记密码           -->
                  <a-form
                      :model="forgetForm"
                      :rules="registerRules"
                      ref="forgetRef"
                      v-if="status === 3"
                      :label-col="labelCol"
                      :wrapper-col="wrapperCol">

                      <a-form-item label="手机号" name="mobile">
                          <a-input-search
                              v-model:value="forgetForm.mobile"
                              placeholder="请输入手机号"
                              enter-button="获取验证码"
                              size="large"
                              :loading=codeLoading
                              @search="getForgetCode"
                          />
                      </a-form-item>
                      <a-form-item label="验证码" name="ssmCode">
                          <a-input v-model:value="forgetForm.ssmCode" placeholder="请输入验证码" />
                      </a-form-item>
                      <a-form-item label="新密码" name="newPassword">
                          <a-input v-model:value="forgetForm.newPassword" placeholder="请输入新密码" />
                      </a-form-item>

                      <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                          <a-button type="primary" @click.prevent="resetPass">重置密码</a-button>
                          <a-button style="margin-left: 10px" @click="backPage">返回</a-button>
                      </a-form-item>
                  </a-form>
              </div>
            </div>
          </div>
          <div class="bottom">
            <div v-if="status == 1">
              还没有账号?
              <span style="font-size: 18px; color: red" @click="toRegister">立即注册</span>
            </div>
            <div v-if="status === 2">
              已有账号?
              <span style="font-size: 18px; color: red" @click="toLogin">返回登录</span>
            </div>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import {defineComponent, ref, UnwrapRef, reactive, toRefs, onMounted,  onUnmounted} from "vue";
import { dateFormat } from '../../untils/date.js'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
    userRegister,
    apiGetCode,
    getImgCode,
    adminLogin,
    apiGetMenu,
    getAllMenu,
    getLoginUserInfo,
    apiForgetPass
} from "../../api";

export default defineComponent({
  name: "login",
  components: {},
  setup() {
    const registerRef = ref()
    const forgetRef = ref()
    const loginRef = ref()
    const router = useRouter()
    const registerForm = reactive({
      email: '',
      mobile: '',
      password: '',
      sex: '',
      username: '',
      code: ''
    })
    const loginForm = reactive({
      // mobile: '15093965952',
      mobile: '13277777777',
      // password: 'zxy',
      password: '1',
      captcha: ''
    })
      // 忘记密码表单
      const forgetForm = reactive({
          mobile: '',
          newPassword: '',
          ssmCode: ''
      })
    const state = reactive({
      timeTimer: undefined,
      time: '',             // 当前时间
      date: '',             // 当前日期
      status: 1,            // 判断是注册还是登录
      codeLoading: false,
      imgUrl: ''
    })

    // 自定义检验邮箱
    let checkEmail = async (rule, value) => {
      if (!value) {
        return Promise.reject('请输入邮箱');
      }
      if (/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请输入合法的邮箱');
      }
    }

    // 自定义检验手机号
    let checkMobile = (rule, value) => {
      if (!value) {
        return Promise.reject('请输入手机号');
      }
      if (/^1[0-9]{10}$/.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请输入合法的手机号');
      }
    }
    // 注册表单检验
    const registerRules = {
      email: [
        { required: true, validator: checkEmail, trigger: 'blur' },
      ],
      mobile: [
        { required: true, validator: checkMobile, trigger: ['blur', 'change'] },
      ],
      username: [
        { required: true, message: '请输入昵称', trigger: 'blur'},
        { min: 1, max: 8, message: '昵称长度在5-10个字直接', trigger: "blur"}
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur'},
      ],
      code: [
        { required: true, message: '请输入短信验证码', trigger: 'blur'},
      ],
      sex: [
        { required: true, message: '请选择性别', trigger: 'blur'},
      ],
        newPassword: [
            { required: true, message: '请输入密码', trigger: 'blur'},
        ],
        ssmCode: [
            { required: true, message: '请输入短信验证码', trigger: 'blur'},
        ],
    }


    // 点击登录按钮
    const onSubmit = () => {
      // 判断表单是否填写
      if (!loginForm.mobile || !loginForm.password || !loginForm.captcha) {
        message.warning('请填写登录相关信息')
        return;
      }
      // 校验手机号是否合法
      const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;    //11位手机号码正则
      if (!regTel.test(loginForm.mobile)) {
        message.warning('请输入合法的手机号')
        return;
      } else {
        // 手机号正确
        const formdata = new FormData()
        // router.push('/index')
        formdata.append('mobile', loginForm.mobile)
        formdata.append('password', loginForm.password)
        formdata.append('captcha', loginForm.captcha)
        adminLogin(formdata).then((res)=>{
          console.log('结果：', res)
          if (res.data.code !== 200) {
            message.warning(res.data.msg)
            return
          } else {
            // 登录成功，获取人员信息，并跳转页面
              // 获取人员信息
              getLoginUserInfo({}).then((res) => {
                  console.log('人员信息为', res.data)
                  if (res.data.code == 200) {
                      const userInfo = JSON.stringify(res.data.data)
                      window.localStorage.setItem('userInfo', userInfo)
                  }
              })
            // 调用获取菜单接口
              apiGetMenu({}).then((res)=>{
              console.log('菜单为：',res)
              if (res.data.code == 200) {
                let menus = JSON.stringify(res.data.data)
                window.localStorage.setItem('meuns', menus)
                message.success('登录成功')
                router.push('/index')
              }
            })

          }
        }).catch((err)=>{
          console.log(err)
        })
      }

    }
    // 点击重置按钮
    const reset = () => {

    }

    // 跳转到注册页面
    const toRegister = () => {
      state.status = 2
      // registerRef.value.resetFields();
    }

    // 点击注册按钮
    const register = () => {
      // 先检验表单是否填写
      registerRef.value
        .validate()
        .then( async ()=> {
          // 验证通过，调用 注册 接口
          // const data = await userRegister(registerForm)
          // console.log('注册结果：', data)
          userRegister(registerForm).then((res)=>{
            console.log(1111, res)
            if (res.data.code === 200) {
              message.success(res.data.msg)
              // 清空信息
              registerRef.value.resetFields();
              state.status = 1
            } else {
              message.error(res.data.msg)
            }
          }).catch((err) => {
            console.log(22222, err)
          }).finally((el) => {
            console.log(333, el)
          })

        })
    }

    // 跳转到登录页面
    const toLogin = () => {
      state.status = 1
    }

    // 获取手机验证码
    const getCode = async () => {
      // 首先判断手机号存不存在
      if (!registerForm.mobile) {
        message.warning('请输入手机号')
        return
      }
      state.codeLoading = true
      if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(registerForm.mobile))) {
        const params = {
          mobile: registerForm.mobile,
          sms_code_method: 'admin_register_sms_code'
        }
        await apiGetCode(params)
        state.codeLoading = false
      } else {
        message.warning('请输入合法的手机号')
        state.codeLoading = false
        return
      }

    }

    // 重置注册表单
    const resetRegister = () => {
      registerRef.value.resetFields();
    }

    // 获取图片验证码
    const getCaptcha = () => {
      getImgCode({}).then((res)=> {
        console.log('结果是：', res)
        // state.imgUrl = res.data
        state.imgUrl = `data: image/jpeg;base64,${btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
      })
    }

    // 获取当前时间
    const getTime = () => {
      state.timeTimer = setInterval(() => {
        state.time = dateFormat(new Date(),'hh:mm:ss');
        state.date = dateFormat(new Date(),'yyyy年MM月dd日');
      }, 1000);
    }

    // 点击验证码刷新验证码
    const refreshCode = () => {
      getCaptcha()
    }

    // 忘记密码
      const forget = () => {
          state.status = 3
      }
      // 重置密码
      const resetPass = () => {
          apiForgetPass(forgetForm).then((res) => {
              if (res.data.code == 200) {
                  message.success('重置密码成功')
                  state.status = 1
                  forgetForm.mobile = ''
                  forgetForm.ssmCode = ''
                  forgetForm.newPassword = ''
              }
          }).catch((err) => {
              message.error('密码修改失败')
              forgetForm.mobile = ''
              forgetForm.ssmCode = ''
              forgetForm.newPassword = ''
          })
      }
      // 返回登录
      const backPage = () => {
        state.status = 1
      }
      // 获取忘记密码验证码
      const getForgetCode = async () => {
          // 首先判断手机号存不存在
          if (!forgetForm.mobile) {
              message.warning('请输入手机号')
              return
          }
          state.codeLoading = true
          if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(forgetForm.mobile))) {
              const params = {
                  mobile: forgetForm.mobile,
                  sms_code_method: 'admin_forget_sms_code'
              }
              const data = await apiGetCode(params)
              console.log(999,data)
              state.codeLoading = false
          } else {
              message.warning('请输入合法的手机号')
              state.codeLoading = false
              return
          }
      }

    onMounted(()=>{
      getTime()
      getCaptcha()
    })

    onUnmounted(()=>{
      clearInterval(state.timeTimer)
    })

    return{
      loginRef,
      registerRef,
      registerForm,
      loginForm,
      ...toRefs(state),
      registerRules,
      labelCol: { span: 5 },
      wrapperCol: { span: 24 },
      onSubmit,
      reset,
      toRegister,
      register,
      toLogin,
      getCode,
      resetRegister,
      refreshCode,
        forget,
        resetPass,
        backPage,
        forgetForm,
        forgetRef,
        getForgetCode
    }
  }
})
</script>

<style lang="less" scoped>
  .login{
    width: 100%;
    height: 100%;

    .content{
      height: 100%;
      background: url("../../assets/img/login/bg.jpg");

      .box{
        width: 60%;
        height: 500px;
        background: #2c3e50;
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);


        .list {
          width: 100%;
          height: 90%;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .left{
            width: 50%;
            height: 100%;
            //background: #42b983;

            .time{
              font-size: 22px;
              color: #fff;
              height: 20%;
              padding-top: 10px;
            }

            img{
              width: 100%;
              height: 80%;
            }
          }

          .right{
            width: 50%;
            height: 100%;
            background: beige;
            padding: 0 15px;
            .form{
              position: relative;
              top: 50%;
              transform: translateY(-50%);

              .code {
                display: flex;
                .captcha{
                  width: 150px;
                  height: auto;
                  //background: green;
                }
              }
            }

          }
        }

        .bottom {
          text-align: center;
          color: #fff;
          padding-top: 10px;
        }

      }


    }
  }
  ::v-deep .ant-radio-group {
    float: left;
  }
</style>
